<!DOCTYPE html>
<html>
    
<head>
    <meta charset="UTF-8">
    <title>ztree高级 增 / 删 / 改 / 移动 节点</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/zTree.v3/3.5.40/css/zTreeStyle/zTreeStyle.css" type="text/css">
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css" type="text/css">
    <script type="text/javascript" src="https://www.layuicdn.com/layui-v2.5.6/layui.all.js"></script>
    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/zTree.v3/3.5.40/js/jquery.ztree.all.min.js"></script>
    <style type="text/css">
        ul.ztree {
            border: 1px solid #617775;
            background: #f0f6e4;
            /*width:300px;*/
            /*height:360px;*/
            overflow-y:scroll;
            overflow-x:auto;
        }
        .ztree li span.button.add {
            margin-left:2px;
            margin-right: -1px;
            background-position:-144px 0;
            vertical-align:top;
            *vertical-align:middle
        }
    </style>
    <script LANGUAGE="JavaScript">
        jQuery.browser = {};
        (function() {
            jQuery.browser.msie = false;
            jQuery.browser.version = 0;
            if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
                jQuery.browser.msie = true;
                jQuery.browser.version = RegExp.$1;
            }
        })();
        var layer = layui.layer;
        var form = layui.form;
        var setting = {
            view: {
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
                selectedMulti: false
            },
            edit: {
                enable: true,
                isMove: true,
                editNameSelectAll: true,
                showRemoveBtn: showRemoveBtn,
                showRenameBtn: true
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: null
                }
            },
            callback: {
                onDrop: onDrop,  // 用于捕获节点拖拽操作结束的事件回调函数  默认值： null
                beforeDrag: beforeDrag,
                beforeRemove: beforeRemove,
                beforeRename: beforeRename
            }
        };

        // var zNodes =[
        //   { id:1, pId:null, name:"父节点 1", open:true},
        //   { id:11, pId:1, name:"叶子节点 1-1"},
        //   { id:12, pId:1, name:"叶子节点 1-2"},
        //   { id:13, pId:1, name:"叶子节点 1-3"},
        //   { id:2, pId:null, name:"父节点 2", open:true},
        //   { id:21, pId:2, name:"叶子节点 2-1"},
        //   { id:22, pId:2, name:"叶子节点 2-2"},
        //   { id:23, pId:2, name:"叶子节点 2-3"},
        //   { id:3, pId:null, name:"父节点 3", open:true},
        //   { id:31, pId:3, name:"叶子节点 3-1"},
        //   { id:32, pId:3, name:"叶子节点 3-2"},
        //   { id:33, pId:3, name:"叶子节点 3-3"}
        // ];

        var zNodes =[ ];

        // 只允许同级节点拖拽的判断是什么
        function beforeDrag(treeId, treeNodes) {
            return true;
        }

        function onDrop(event, treeId, treeNodes, targetNode, moveType) {
            //拖拽成功时，修改被拖拽节点的pid
            console.log(event);
            console.log("拖动的节点ID  "+treeNodes[0].id+" 名称  "+treeNodes[0].name)
            console.log(treeNodes); //
            console.log(treeNodes[0].pId);
            console.log(targetNode);
            console.log(moveType);  // prev, inner, next
            // 该节点ID, 目标节点ID, moveType
            console.log("\n\n");
        }

        function beforeRemove(treeId, treeNode) {
            layer.confirm("确认删除 节点 -- " + treeNode.name + " 吗？", {
                btn: ['确定', '取消'] ,
                // btn: ['按钮1', '按钮2']
                btn1: function (index) {
                    // 按钮1的事件
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    zTree.removeNode(treeNode);
                    layer.close(index);
                }, 
                btn2: function(index) {
                    // 按钮2的事件
                    layer.close(index);
                }
            });
            return false;
        }

        function beforeRename(treeId, treeNode, newName, isCancel) {
            if (newName.length == 0) {
                setTimeout(function() {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    zTree.cancelEditName();
                    layer.msg('节点名称不能为空', {
                        time: 1000 //2秒关闭（如果不配置，默认是3秒）
                    }, function() {
                    //do something
                    });
                }, 0);
                return false;
            }
            return true;
        }

        function showRemoveBtn(treeId, treeNode) {
            return treeNode.children==null;;
        }

        var newCount = 1;
        function addHoverDom(treeId, treeNode) {
            var sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='add node' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = $("#addBtn_" + treeNode.tId);
            if (btn) btn.bind("click", function() {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                zTree.addNodes(treeNode, {
                    id: (100 + newCount),
                    pId: treeNode.id,
                    name: "new node" + (newCount++)
                });
                // console.log(JSON.stringify(assemblyTreeData(zTree.getNodes()))+"\n\n\n");
                return false;
            });
        }

        function removeHoverDom(treeId, treeNode) {
            $("#addBtn_" + treeNode.tId).unbind().remove();
        }

        $(function() {
            $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        })

        // 添加顶层节点
        function addTopLevelNode() {
            var zTree = $.fn.zTree.getZTreeObj("treeDemo");
            zTree.addNodes(null, {
                id: (100 + newCount),
                pId: null,
                name: "new node" + (newCount++)
            });
            layer.msg("点击事件");
        }

        function assemblyTreeData(treeNodes) {
            var newTreeNodes = [];
            for (var i in treeNodes) {
                var item = treeNodes[i];
                var newItem = {
                    "id": item["id"],
                    "name": item["name"],
                    "pId": item["pId"]
                };
                if (item.children!=null && item.children.length > 0) {
                    newItem["children"] = assemblyTreeData(item.children)
                }
                newTreeNodes.push(newItem);
            }
            return newTreeNodes;
        }
    </script>
</head>

<body>
<div>
    <div class="layui-row layui-col-space5">
        <div class="layui-col-xs3 layui-col-sm3 layui-col-md3 layui-col-lg3">
            <div style="padding: 2px 15px;">
                <button type="button" class="layui-btn layui-btn-xs" onclick="addTopLevelNode()">添加根节点</button>
            </div>
            <ul id="treeDemo" class="ztree"></ul>
        </div>
        <div class="layui-col-xs3 layui-col-sm3 layui-col-md3 layui-col-lg3">
            <div style="background-color: #63BA79; color: #fff;">3/12</div>
        </div>
        <div class="layui-col-xs3 layui-col-sm3 layui-col-md3 layui-col-lg3">
            <div style="background-color: #79C48C; color: #fff;">3/12</div>
        </div>
        <div class="layui-col-xs3 layui-col-sm3 layui-col-md3 layui-col-lg3">
            <div style="background-color: #63BA79; color: #fff;">3/12</div>
        </div>
    </div>
</div>
</body>

</html>